<?php
class People extends Controller {

	function People()
	{
		parent::Controller();	
		$this->users->checkAdmin();
		$this->load->helper('file');
	}

	//All the users management
	function edit () 
	{
			$data['query'] = $this->db->query('SELECT * FROM users WHERE id = "'. $this->uri->segment(3) . '"');
			$template['content'] = $this->load->view('admin_usersedit', $data, TRUE);
			$template['title'] = "Edit User";
			$template['tabs'] = array ( anchor('people', 'back to user management'));
			$this->load->view('template', $template);
	}
	function delete ()
	{
			$user = $this->uri->segment(3);
			$this->db->where('id', $user);
			$this->db->delete('users'); 
			redirect('people');
	}
	function index() 
	{
			$this->load->library('validation');
			$data['users'] = $this->db->query('SELECT * FROM users');
			
			//Set the validation rules
			$rules['username'] = "required";
			$rules['fname'] = "required";
			$rules['pass'] = "required|matches[pass2]";
			$rules['pass2'] = "required";
			$rules['email'] = "required|valid_email";
			$this->validation->set_rules($rules);

			$this->validation->set_error_delimiters('<span class="error">', '</span>');
			$this->validation->set_message('required', 'required');

			//Give the fields sensible names for the validator
			$fields['username'] = 'Username';
			$fields['pass'] = 'Password';
			$fields['pass2'] = 'Password Confirmation';
			$fields['email'] = 'Email Address';
			$this->validation->set_fields($fields);

			if ($this->validation->run() == FALSE)
			{
				$template['content'] = $this->load->view('admin_users', $data, TRUE);
			}
			else
			{
				$this->db->set('username', $_POST['username']);
				$this->db->set('fname', $_POST['fname']);
				$this->db->set('email', $_POST['email']);
				$this->db->set('password', $this->encrypt->encode($_POST['pass']));
				$this->db->set('isadmin', $_POST['admin']);
				$this->db->insert('users');
				redirect('people');
			}

			$template['title'] = "Users";
			$this->load->view('template', $template);
	}
	function save_user() 
	{
		$this->db->set('fname', $_POST['fname']);
		$this->db->set('email', $_POST['email']);
		if ($_POST['pass'] == '') {
		}
		elseif ($_POST['pass'] === $_POST['pass2'])
		{
		$this->db->set('password', $this->encrypt->encode($_POST['pass']));
		}
		else 
		{
		echo 'the passwords you entered are not the same';
		}
		$this->db->set('isadmin', $_POST['admin']);
		$this->db->where('id', $_POST['user']);
		$this->db->update('users');
		redirect('people');
	}
}
?>